package com.blank.client;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScreenShotClient extends JFrame implements MouseMotionListener, MouseListener {

	private JPanel drawPl = new JPanel();

	int startx, starty, endx, endy, pstartx, pstarty, pendx, pendy;// 起始坐标与终点坐标

	private static final long serialVersionUID = 1L;

	private Toolkit tool = this.getToolkit();

	private String flag = null;

	private BufferedImage image;

	private File img = new File("a.png");

	private JButton finishBt = new JButton("√完成");
	private JButton cancelBt = new JButton("X");

	private boolean canDragger = true;

	public void updateImg() {

		try {

			image = ImageIO.read(img);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	};

	public ScreenShotClient() {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		this.add(finishBt);
		this.add(cancelBt);
		this.setSize(d.width, d.height);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(null);
		this.add(drawPl);
		this.setAlwaysOnTop(true);
		finishBt.setFocusable(false);
		cancelBt.setFocusable(false);
		drawPl.setBounds(0, 0, d.width, d.height);
		drawPl.addMouseListener(this);
		drawPl.addMouseMotionListener(this);
		
		cancelBt.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				cancel();
			}
		});
		
		finishBt.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {	
				setClipboardImage(cutBufferedImage(image, pstartx, pstarty, pendx-pstartx, pendy-pstarty));
				cancel();
				ScreenShotClient.this.setVisible(false);
			}
		});
		
		this.addKeyListener(new KeyAdapter() {

			public void keyPressed(KeyEvent e) {
				int code = e.getKeyCode();
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					ScreenShotClient.this.setVisible(false);
					flag = null;
				}
			}
		});

	}
	
	public void setClipboardImage(final Image image) {  
        Transferable trans = new Transferable() {  
            public DataFlavor[] getTransferDataFlavors() {  
                return new DataFlavor[] { DataFlavor.imageFlavor };  
            }  
  
            public boolean isDataFlavorSupported(DataFlavor flavor) {  
                return DataFlavor.imageFlavor.equals(flavor);  
            }  
  
            public Object getTransferData(DataFlavor flavor)  
                    throws UnsupportedFlavorException, IOException {  
                if (isDataFlavorSupported(flavor))  
                    return image;  
                throw new UnsupportedFlavorException(flavor);  
            }  
  
        };  
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans, null);  

      
    }  
	
	  public BufferedImage cutBufferedImage(BufferedImage srcBfImg, int x, int y, int width, int height) {
	        BufferedImage cutedImage = null;
	        CropImageFilter cropFilter = new CropImageFilter(x, y, width, height);  
	        Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(srcBfImg.getSource(), cropFilter));  
	        cutedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
	        Graphics g = cutedImage.getGraphics();  
	        g.drawImage(img, 0, 0, null);  
	        g.dispose(); 
	        return cutedImage;
	    }

	@Override
	public void mouseDragged(MouseEvent arg0) {

		// endx = Math.abs(arg0.getX() - startx);
		// endy = Math.abs(arg0.getY() - starty);
		pendx = arg0.getX();
		pendy = arg0.getY();
		pstartx = startx;
		pstarty = starty;

		if (startx > pendx) {
			int temp = 0;
			temp = pstartx;
			pstartx = pendx;
			pendx = temp;
		}

		if (starty > pendy) {
			int temp = 0;
			temp = pstarty;
			pstarty = pendy;
			pendy = temp;
		}

		update(getGraphics());

	}

	public void update(Graphics g) {

		Image ImageBuffer = null;
		Graphics GraImage = null;
		// 覆盖update方法，截取默认的调用过程
		ImageBuffer = createImage(this.getWidth(), this.getHeight()); // 创建图形缓冲区
		GraImage = ImageBuffer.getGraphics(); // 获取图形缓冲区的图形上下文
		paint(GraImage); // 用paint方法中编写的绘图过程对图形缓冲区绘图
		GraImage.dispose(); // 释放图形上下文资源
		g.drawImage(ImageBuffer, 0, 0, this); // 将图形缓冲区绘制到屏幕上
	}

	public void paint(Graphics g) { // 在paint方法中实现绘图过程
		Graphics2D g2 = (Graphics2D) g;
		g2.drawImage(image, 0, 0, image.getWidth(this), image.getHeight(this), drawPl);
		if (flag == null || flag.equals("clean")) {
			return;
		}

		else if (flag.equals("Dragged")) {

			g2.setColor(new Color(0, 0, 0, 0.4f));
			g2.fillRect(0, 0, image.getWidth(), pstarty);
			g2.fillRect(0, pstarty, pstartx, pendy - pstarty);
			g2.fillRect(pendx, pstarty, image.getWidth() - pendx, pendy - pstarty);
			g2.fillRect(0, pendy, image.getWidth(), image.getHeight() - pendy);

			g2.setStroke(new BasicStroke(1.0f));
			g2.setColor(Color.blue);
			g2.drawRect(pstartx, pstarty, pendx - pstartx, pendy - pstarty);
		}

	}

	@Override
	public void mouseMoved(MouseEvent arg0) {

	}
	
	public void cancel(){
		flag = null;
		update(getGraphics());
		finishBt.setVisible(false);
		cancelBt.setVisible(false);
		drawPl.addMouseMotionListener(this);
		repaint();
		canDragger = true;
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON3) {
			if(flag==null)
				{this.setVisible(false);return;}
			cancel();

		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON1 && canDragger == true) {
			startx = e.getX();
			starty = e.getY();
			flag = "Dragged";
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		if (e.getButton() == MouseEvent.BUTTON1 && canDragger == true && e.getX() != startx && e.getY() != starty) {
			endx = e.getX();
			endy = e.getY();
			finishBt.setBounds(pendx-80, pendy-20, 80, 20);
			cancelBt.setBounds(pendx-120,pendy-20,40,20);
			finishBt.setVisible(true);
			cancelBt.setVisible(true);
			drawPl.removeMouseMotionListener(this);
			canDragger = false;
		}
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
	}

}
